﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComLib.ComType;
using IPrinting;
using LogLib;
using PhotoPrintClient;

namespace KWindow.KPageCore
{
    public class PrintControl : IDisposable
    {
        /// <summary>
        /// 请求控制的打印设备名称
        /// </summary>
        private string _printerName = "";

        private string _error = "";
        public string Error
        {
            get { return _error; }
        }

        private PrintClient _client = new PrintClient();

        #region To do something(delegate) after receive response from DeviceManageServer
        public DoSomething OnInitOK { get; set; }
        public DoSomething OnInitFailed { get; set; }
        public DoSomething OnExitOK { get; set; }
        public DoSomething OnExitFailed { get; set; }
        public DoSomething OnPrintOK { get; set; }
        public DoSomething OnPrintFailed { get; set; }
        public DoSomething OnCropPrintOK { get; set; }
        public DoSomething OnCropPrintFailed { get; set; }
        public DoSomething OnClearOK { get; set; }
        public DoSomething OnClearFailed { get; set; }
        public DoSomething OnTimeout { get; set; }
        public DoSomething OnCatchException { get; set; }
        #endregion

        public PrintControl(string name)
        {
            _printerName = name;
            InitDelegateFuncs();
        }

        /// <summary>
        /// 初始化所有的委托方法的对象
        /// 如果预测要使用该方法，必须在外部对其重新赋值
        /// </summary>
        private void InitDelegateFuncs()
        {
            // 以下委托必须在外部实现
            OnPrintFailed = OnNotImplemented;
            OnPrintOK = OnNotImplemented;
            OnCropPrintOK = OnNotImplemented;
            OnCropPrintFailed = OnNotImplemented;
            OnCatchException = OnNotImplemented;

            // 如果没有调用相关动作，以下委托可以不实现，
            // 但是如果有调用相关动作，必须实现对应动作请求返回后的回调
            // 否则将抛出异常
            OnInitOK = OnDefaultAction;
            OnInitFailed = OnDefaultAction;
            OnExitFailed = OnDefaultAction;
            OnExitOK = OnDefaultAction;
            OnClearFailed = OnDefaultAction;
            OnClearOK = OnDefaultAction;
            OnTimeout = OnDefaultAction;         
        }

        private void OnDefaultAction(string outstring)
        {

        }

        private void OnNotImplemented(string delegateFunName)
        {
            throw new NotImplementedException();
        }

        public bool Init()
        {
            _client.ConnectToServer();
            if (_client.Connected)
            {
                _client.ClientPackageReceived += NewPackage_Received;
                _client.ErrorReported += ClientError_Reported;
                Log.WriteAsync("客户端连接成功!");
                return true;
            }
            else
            {
                Log.WriteAsync("客户端连接失败!");
                return false;
            }
        }

        public void Exit()
        {
            Dispose();
        }

        private void ClientError_Reported(object sender, ErrorReportedEventArgs e)
        {
            _error = "客户端连接发生了异常: " + e.Message;
            Log.WriteAsync(_error);
        }

        private void NewPackage_Received(object sender, PrintClientPackageReceivedEventArgs e)
        {
            _error = "";
            PrintResponsePackge package = e.Package;
            PrintResult action = package.Result;
            string outParams = package.OutParams;
            string errorMsg = package.Message;
            switch (action)
            {
                case PrintResult.InitOK:
                    OnInitOK(outParams);
                    break;
                case PrintResult.InitFailed:
                    OnInitFailed(errorMsg);
                    break;
                case PrintResult.ExitOK:
                    OnExitOK(outParams);
                    break;
                case PrintResult.ExitFailed:
                    OnExitFailed(errorMsg);
                    break;
                case PrintResult.PrintOK:
                    OnPrintOK(outParams);
                    break;
                case PrintResult.PrintFailed:
                    OnPrintFailed(errorMsg);
                    break;
                case PrintResult.CropPrintOK:
                    OnCropPrintOK(outParams);
                    break;
                case PrintResult.CropPrintFailed:
                    OnCropPrintFailed(errorMsg);
                    break;
                case PrintResult.ClearOK:
                    OnClearOK(outParams);
                    break;
                case PrintResult.ClearFailed:
                    OnClearFailed(errorMsg);
                    break;
                case PrintResult.Timeout:
                    OnTimeout(errorMsg);
                    break;
                case PrintResult.CatchException:
                    OnCatchException(errorMsg);
                    break;
                default:
                    break;
            }
        }

        #region Device general controls 请求控制设备的基本操作

        /// <summary>
        /// 请求控制设备执行某个动作
        /// </summary>
        /// <param name="action"></param>
        /// <param name="inParams"></param>
        protected void TakeAction(string action, string inParams)
        {
            if (!_client.Connected)
            {
                return;
            }
            PrintDataPackge pack = new PrintDataPackge();
            pack.Invoker = _printerName;
            pack.Action = action;
            pack.InParams = inParams;
            _client.SendRequest(pack);
        }

        /// <summary>
        ///  发送裁切和打印照片请求
        /// </summary>    
        /// <param name="inParams">请求控制需要输入的参数</param>
        public void CropPrint(string inParams = "")
        {
            TakeAction(PrintAction.CropPrint, inParams);
        }

        /// <summary>
        ///  发送打印照片请求
        /// </summary>
        /// <param name="inParams">请求控制需要输入的参数</param>
        public void Print(string inParams = "")
        {
            TakeAction(PrintAction.Print, inParams);
        }

        /// <summary>
        /// 请求设备执行操作(one motion)
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="inParams"></param>
        public void Init(string inParams = "")
        {
            TakeAction(PrintAction.Init, inParams);
        }

        /// <summary>
        /// 卸载设备(一般在业务流程中不用)
        /// </summary>
        /// <param name="inParams"></param>
        public void Exit(string inParams = "")
        {
            TakeAction(PrintAction.Init, inParams);
        }

        /// <summary>
        /// 清理打印任务
        /// </summary>
        /// <param name="inParams">输入参数</param>
        public void Clear(string inParams = "")
        {
            TakeAction(PrintAction.Clear, inParams);
        }

        public void ExitApp(string inParams = "")
        {
            TakeAction(PrintAction.ExitApp, inParams);
        }

        #endregion

        public void Dispose()
        {
            _client.Close();
        }
    }
}
